package com.openswimsoftware.orm.model.query;

import java.lang.reflect.Field;

import com.openswimsoftware.orm.ORM;
import com.openswimsoftware.orm.model.Model;
import com.openswimsoftware.orm.model.annotation.Child;
import com.openswimsoftware.orm.model.annotation.Children;
import com.openswimsoftware.orm.model.list.ModelList;

import android.content.ContentValues;
import android.content.Context;
import android.util.Log;

public class ModelSave<E extends  Model<E>> extends ModelQuery<E, ModelSave<E>> {
	
	public ModelSave(Context context, Class<E> modelType, E model)
	{
		super(context, modelType, model);
	}
	
	public E execute()
	{	
		try
		{
			this.dbInterface.openDB();
			
			if (this.model.getId() == -1)
			{
				this.create();
			}
			else
			{
				this.save();
			}
		
			this.dbInterface.closeDB();
			
			if (this.model.getId() != -1)
			{
				this.model.setUpdated(false);
				this.model.setLoaded(false);
				
				for (Field field: ORM.getRelationshipFields(modelType))
				{
					field.setAccessible(true);
					
					if (field.isAnnotationPresent(Child.class))
					{
						if (field.get(this.model) != null)
						{
							((Model<?>) field.get(this.model)).save();
						}
					}
					else if (field.isAnnotationPresent(Children.class))
					{
						if (field.get(this.model) != null)
						{
							((ModelList<?>) field.get(this.model)).save();
						}
					}
				}
				
				return this.model;
			}
		} 
		catch (IllegalArgumentException e) 
		{
			e.printStackTrace();
		} 
		catch (IllegalAccessException e) 
		{
			e.printStackTrace();
		}
		
		return null;
	}
	
	private void create() throws IllegalArgumentException, IllegalAccessException
	{
		String table = ORM.tableName(this.modelType);
			
		Log.d("orm", "Creating " + this.modelType.getSimpleName());
			
		ContentValues values = this.model.toContent();
		this.model.setId(this.dbInterface.getDB().insert(table, null, values));
	}
	
	private void save() throws IllegalArgumentException, IllegalAccessException
	{
		String table = ORM.tableName(this.modelType);
		String where = "_ID = ?";
		String[] whereArgs = new String[]{ this.model.getId()+"" };
					
		Log.d("orm", "Saving " + this.modelType.getSimpleName() + " with id " + this.model.getId()+"");
					
		ContentValues values = this.model.toContent();
		this.dbInterface.getDB().update(table, values, where, whereArgs);
	}

}
